#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <unistd.h>

void get_cpuid(long num_processors)
{
    int ret;
    size_t cpusize;
    cpu_set_t cpuset;

    cpusize = sizeof(cpu_set_t);
    ret = sched_getaffinity(0, cpusize, &cpuset);
    if (ret != 0) {
        perror("sched_getaffinity");
        return;
    }

    for (size_t i = 0; i < num_processors; i++) {
        if (CPU_ISSET(i, &cpuset)) {
            printf("Current process is bound to CPU core %zu.\n", i);
            break;
        }
    }
}

int main() {
    long num_processors;

    num_processors = sysconf(_SC_NPROCESSORS_ONLN);
    if (num_processors == -1) {
        perror("sysconf");
        return 1;
    }
    printf("Total number of CPUs: %ld\n", num_processors);

    while(1) {
      sleep(3);
      get_cpuid(num_processors);
    }
    return 0;
}
